package com.fxm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxm.dao.VisitMapper;
import com.fxm.domain.Visit;
import com.fxm.returns.RespCode;
import com.fxm.returns.RespEntity;
import com.fxm.service.VisitService;
import com.fxm.vo.result.VisitResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 访问量表 服务实现类
 * </p>
 *
 * @author fxm
 * @since 2021-02-24
 */
@Slf4j
@Service
public class VisitServiceImpl extends ServiceImpl<VisitMapper, Visit> implements VisitService {

    @Override
    public RespEntity<VisitResult> visitList() {

        //最近24小时访问量数据
        List<Visit> hourVisitList = baseMapper.listRecent24HVisit();

        //最近30日访问量数据
        List<Visit> dayVisitList = baseMapper.listRecent30DaysVisit();

        //数据组装
        VisitResult visitResult = dataPackage(hourVisitList, dayVisitList);

        return new RespEntity(RespCode.SUCCESS, visitResult);
    }

    /**
     * 数据组装
     * @param hourVisitList
     * @param dayVisitList
     * @return
     */
    private VisitResult dataPackage(List<Visit> hourVisitList, List<Visit> dayVisitList) {

        //近24小时日期集合
        List<String> hourDateList = hourVisitList.stream().map(Visit::getDt).collect(Collectors.toList());
        hourDateList = hourDateList.stream().map(v -> {
            String[] split = v.split("\\s+")[1].split(":");
            return split[0] + ":" + split[1];
        }).collect(Collectors.toList());

        //近24小时访问量集合
        List<Integer> hourValueList = hourVisitList.stream().map(Visit::getVisit).collect(Collectors.toList());
        //近24小时访问量最大值
        Integer hourMaxValue = hourValueList.stream().max(Integer::compareTo).get();

        //近30天日期集合
        List<String> dayDateList = dayVisitList.stream().map(Visit::getDtD).collect(Collectors.toList());
        dayDateList = dayDateList.stream().map(v -> {
            String[] split = v.split("-");
            return split[1] + "-" + split[2];
        }).collect(Collectors.toList());

        //近30天访问量集合
        List<Integer> dayValueList = dayVisitList.stream().map(Visit::getVisit).collect(Collectors.toList());
        //近30天访问量最大值
        Integer dayValueMax = dayValueList.stream().max(Integer::compareTo).get();

        return new VisitResult(hourMaxValue, hourDateList, hourValueList, dayValueMax, dayDateList, dayValueList);
    }
}
